package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.factory.MarketingFieldHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.FieldAttrEntityForImport;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.vo.AfterSaveVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.service.PromotionActivityService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.MarketingErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.listbatch.pojo.dto.OnlineDTO;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.marketing.pojo.dto.MarketingManagementDataAddDTO;
import com.xbongbong.pro.marketing.pojo.dto.MarketingManagementDataUpdateDTO;
import com.xbongbong.pro.marketing.pojo.dto.MarketingManagementDeleteBatchDTO;
import com.xbongbong.pro.marketing.pojo.vo.MarketingManagementDeleteBatchVO;
import com.xbongbong.pro.message.constant.MarketingManagementPushConstant;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.DistributorMessageRabbitMqDTO;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.rabbitmq.producer.BaseProducer;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.domain.entity.PromotionActivityEntity;
import com.xbongbong.saas.domain.entity.PromotionProductEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.MarketingBaseEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.PromotionActivityManagementEnum;
import com.xbongbong.saas.enums.dictionary.MarketingStatusEnum;
import com.xbongbong.saas.help.MarketingHelp;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.PromotionActivityModel;
import com.xbongbong.saas.model.PromotionProductModel;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 创建时间： 2021/1/5 16:44
 * @author jyh
 */
@Service("PromotionActivityService")
public class PromotionActivityServiceImpl implements PromotionActivityService {


    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private PromotionActivityModel promotionActivityModel;
    @Resource
    private PromotionProductModel promotionProductModel;
    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private MarketingHelp marketingHelp;
    @Resource
    private LogHelp logHelp;
    @Resource
    private MarketingFieldHelp marketingFieldHelp;
    @Resource
    private ProductModel productModel;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private UserModel userModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private BaseProducer baseProducer;

    private static final Logger LOG = LoggerFactory.getLogger(PromotionActivityServiceImpl.class);

    @Override
    public AfterSaveVO add(MarketingManagementDataAddDTO marketingManagementDTO) throws XbbException {
        JSONObject dataList = marketingManagementDTO.getDataList();
        Integer businessType = marketingManagementDTO.getBusinessType();
        JSONArray productArray = beforeSave(dataList, businessType, false, marketingManagementDTO.getCorpid(), null);
        marketingManagementDTO.setProductArray(productArray);
        AfterSaveVO afterSaveVO = insert(marketingManagementDTO);
        return afterSaveVO;

    }

    @Override
    public void syncCategory(Long categoryId, Long productId, String corpid) {
        try {
            promotionProductModel.updateCategorybyProductId(categoryId, productId, corpid);
        } catch (Exception e) {
            LOG.error("PromotionActivityServiceImpl同步跟新产品分类出错", e);
        }
    }

    @Override
    public MarketingManagementDeleteBatchVO deleteBatch(MarketingManagementDeleteBatchDTO marketingManagementDeleteBatchDTO) throws XbbException {

        MarketingManagementDeleteBatchVO marketingManagementDeleteBatchVO = new MarketingManagementDeleteBatchVO();
        List<Long> dataIdList = marketingManagementDeleteBatchDTO.getDataIdList();
        String corpid = marketingManagementDeleteBatchDTO.getCorpid();
        if (Objects.equals(dataIdList.size(), BasicConstant.ONE)) {
            Long id = dataIdList.get(0);
            PromotionActivityEntity promotionActivityEntity = promotionActivityModel.getByKey(id, corpid);
            if (!Objects.equals(promotionActivityEntity.getStatus(), MarketingStatusEnum.WAIT_ONLINE.getCode())) {
                throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500006);
            }
            promotionActivityModel.deleteByKey(id, corpid);
            promotionProductModel.deleteByRefId(id, corpid);
            String userName = marketingManagementDeleteBatchDTO.getLoginUserName();
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(promotionActivityEntity.getBusinessType());
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_WORK), userName, xbbRefTypeEnum.getName(), promotionActivityEntity.getName());
            mongoLogHelp.buildLog(corpid, marketingManagementDeleteBatchDTO.getUserId(), userName, OperateModuleTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT, OperateTypeEnum.DELETE,
                    promotionActivityEntity.getId().toString(), promotionActivityEntity.getName(), memo, marketingManagementDeleteBatchDTO.getHttpHeader());
        }
        marketingManagementDeleteBatchVO.setDeleteIds(dataIdList);
        return marketingManagementDeleteBatchVO;
    }

    @Override
    public AfterSaveVO update(MarketingManagementDataUpdateDTO marketingManagementDTO) throws XbbException {

        AfterSaveVO afterSaveVO = new AfterSaveVO();
        JSONObject data = marketingManagementDTO.getDataList();
        String corpid = marketingManagementDTO.getCorpid();
        Integer businessType = marketingManagementDTO.getBusinessType();
        Long dataId = marketingManagementDTO.getDataId();
        PromotionActivityEntity oldPromotionActivityEntity = promotionActivityModel.getByKey(dataId, corpid);
        JSONArray productArray = beforeSave(data, businessType, true, corpid, oldPromotionActivityEntity);
        if (!Objects.equals(oldPromotionActivityEntity.getStatus(), MarketingStatusEnum.WAIT_ONLINE.getCode())) {
            throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500009);
        }
        PromotionActivityEntity promotionActivityEntity = new PromotionActivityEntity();
        data.put(MarketingBaseEnum.STATUS.getAttr(), MarketingStatusEnum.WAIT_ONLINE.getCode());
        promotionActivityEntity.setName(data.getString(MarketingBaseEnum.NAME.getAttr()));
        promotionActivityEntity.setCorpid(corpid);
        promotionActivityEntity.setData(data);
        promotionActivityEntity.setStatus(MarketingStatusEnum.WAIT_ONLINE.getCode());
        promotionActivityEntity.setBusinessType(businessType);
        promotionActivityEntity.setBeginTime(data.getLong(MarketingBaseEnum.BEGIN_TIME.getAttr()));
        promotionActivityEntity.setEndTime(data.getLong(MarketingBaseEnum.END_TIME.getAttr()));
        promotionActivityEntity.setPriority(data.getInteger(MarketingBaseEnum.PRIORITY.getAttr()));
        promotionActivityEntity.setId(oldPromotionActivityEntity.getId());
        promotionActivityEntity.setCreatorId(oldPromotionActivityEntity.getCreatorId());
        promotionActivityModel.update(promotionActivityEntity);
        saveProduct(promotionActivityEntity, productArray, corpid, true);
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        String userName = marketingManagementDTO.getLoginUserName();
        String logName = promotionActivityEntity.getName();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        JSONObject oldObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(oldPromotionActivityEntity));
        JSONObject newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(promotionActivityEntity));
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_WORK),userName, xbbRefTypeEnum.getName(),logName);
        List<DetailLogPojo> detailArr = logHelp.getDetailArr4Data(corpid, redundantTemplateTypeEnum, marketingFieldHelp.getFieldMapByBusinessType(businessType), oldObj, newObj);
        mongoLogHelp.buildLog4DetailArr(detailArr, corpid, marketingManagementDTO.getUserId(), userName, OperateModuleTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT, OperateTypeEnum.EDIT,
                dataId.toString(), promotionActivityEntity.getName(), memo, marketingManagementDTO.getHttpHeader());
        afterSaveVO.setFormDataId(promotionActivityEntity.getId());
        return afterSaveVO;
    }

    @Override
    public void formatExportValue(List<PaasFormDataEntityExt> paasFormDataESList, FormDataListDTO formDataListDTO, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {

        // 所有产品map
        List<Long> idList = new ArrayList<>();
        paasFormDataESList.forEach(item -> idList.add(item.getDataId()));
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID, formDataListDTO.getCorpid());
        params.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        params.put("refIdIn", idList);
        params.put("orderByStr","sort");
        List<PromotionProductEntity> entities = promotionProductModel.findEntities(params);

        Map<Long, List<PromotionProductEntity>> promotionProductMap = new HashMap<>();
        List<Long> productIdList = new ArrayList<>();
        entities.forEach(item -> {
            Long refId = item.getRefId();
            List<PromotionProductEntity> promotionProductEntities = promotionProductMap.getOrDefault(refId, new ArrayList<>());
            promotionProductEntities.add(item);
            promotionProductMap.put(refId, promotionProductEntities);
            productIdList.add(item.getProductId());
            productIdList.add(item.getParentId());
        });

        Map<Long, ProductEntityExt> productMap = productModel.getProductMapByIdIn(formDataListDTO.getCorpid(), productIdList, DelEnum.NORMAL.getDel());

        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
            JSONObject formDataObj = paasFormDataEntityExt.getData();
            Long dataId = paasFormDataEntityExt.getDataId();
            List<PromotionProductEntity> promotionProductEntityList = promotionProductMap.get(dataId);
            if (promotionProductEntityList == null || promotionProductEntityList.size() == 0) {
                formDataObj.put(PromotionActivityManagementEnum.APPLICABLE_PRODUCT.getAttr(), new JSONArray());
                continue;
            }
            JSONArray productArray = new JSONArray();
            for (PromotionProductEntity promotionProductEntity : promotionProductEntityList) {
                JSONObject productObj = new JSONObject();
                Long productId = promotionProductEntity.getProductId();
                ProductEntityExt productEntity = productMap.get(productId);
                JSONObject productJson = productEntity.getData();
                String name = productJson.getString(ProductEnum.NAME.getAttr());
                productObj.put(SelectProductEnum.PRODUCT_NAME.getAttr(), name);
                String productNo = productJson.getString(ProductEnum.PRODUCT_NO.getAttr());
                Long parentId = productJson.getLong(ProductEnum.PARENT_ID.getAttr());
                if (parentId != null && parentId != 0L && productMap.containsKey(parentId)) {
                    ProductEntityExt parentProduct = productMap.get(parentId);
                    productNo = parentProduct.getSerialNo();
                }
                productObj.put(SelectProductEnum.PRODUCT_NO.getAttr(), productNo);
                String spec = productJson.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
                productObj.put(SelectProductEnum.SPECIFICATION.getAttr(), spec);
                if (StringUtil.isNotEmpty(spec) && Objects.equals(spec, "{}")) {
                    productObj.put(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                }
                productObj.put(SelectProductEnum.DISCOUNT.getAttr(), promotionProductEntity.getDiscount());
                productArray.add(productObj);
            }
            formDataObj.put(PromotionActivityManagementEnum.APPLICABLE_PRODUCT.getAttr(), productArray);
        }
    }

    @Override
    public void online(OnlineDTO onlineDTO) throws XbbException {
        String corpid = onlineDTO.getCorpid();
        List<Long> dataIdList = onlineDTO.getDataIdList();
        Long dataId = dataIdList.get(0);
        // 上下架 1上架0下架
        Integer online = onlineDTO.getOnline();
        if (Objects.equals(online, 1) && !onlineDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.PROMOTION_ACTIVITY_ON.getAlias())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050.getCode(), String.format(SystemErrorCodeEnum.API_ERROR_100050.getMsg(), ProPermissionAliasEnum.PROMOTION_ACTIVITY_ON.getMemo()));
        }else if (Objects.equals(online, 0) && !onlineDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.PROMOTION_ACTIVITY_OFF.getAlias())){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050.getCode(), String.format(SystemErrorCodeEnum.API_ERROR_100050.getMsg(), ProPermissionAliasEnum.PROMOTION_ACTIVITY_OFF.getMemo()));
        }
        String key = corpid + "_" + dataId;
        //上下架日志
        String userId = onlineDTO.getUserId();
        String userName = onlineDTO.getLoginUserName();
        PromotionActivityEntity promotionActivityEntity = promotionActivityModel.getByKey(dataId, corpid);
        try {
            Long incrNum = paasRedisHelper.getIncrNum(RedisPrefixConstant.PROMOTION_ONLINE_KEY, key, TimeConstant.SECONDS_PER_MINUTE, 1, 1);
            if (incrNum > 1) {
                throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500034);
            }
            long now = DateTimeUtil.getInt();
            Long endTime = promotionActivityEntity.getEndTime();
            JSONObject data = promotionActivityEntity.getData();
            if ((Objects.equals(online, BasicConstant.ONE))) {
                //判断活动是否下架，下架的不能在上架
                if (Objects.equals(promotionActivityEntity.getStatus(), MarketingStatusEnum.OFFLINE.getCode())) {
                    throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500033);
                }
                //同时上架的活动不能超过50个
                Integer promotionCount = promotionActivityModel.getOnlinePromotionCount(corpid);
                if (promotionCount >= BasicConstant.PROMOTION_MAX_COUNT) {
                    throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500031);
                }
                //判断活动是否过期
                if (endTime < DateTimeUtil.getTodayInt()) {
                    throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500032);
                }
                promotionActivityEntity.setStatus(MarketingStatusEnum.ONLINE.getCode());
                data.put(MarketingBaseEnum.STATUS.getAttr(),MarketingStatusEnum.ONLINE.getCode());
            }else if ((Objects.equals(online, BasicConstant.ZERO))){
                //下架移除
                promotionActivityEntity.setStatus(MarketingStatusEnum.OFFLINE.getCode());
                data.put(MarketingBaseEnum.STATUS.getAttr(),MarketingStatusEnum.OFFLINE.getCode());
            }
            promotionActivityModel.update(promotionActivityEntity);
            OperateTypeEnum operateTypeEnum = Objects.equals(online, 1) ? OperateTypeEnum.ONLINE : OperateTypeEnum.OFFLINE;
            String onlyOnline = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ONLINE), userName, XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getName(), promotionActivityEntity.getName());
            String onlyOffline = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_OFFLINE), userName, XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getName(), promotionActivityEntity.getName());
            String memo = Objects.equals(online, 1) ? onlyOnline : onlyOffline;
            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT, operateTypeEnum,
                    promotionActivityEntity.getId().toString(), promotionActivityEntity.getName(), memo, onlineDTO.getHttpHeader());
            paasRedisHelper.removeValue(RedisPrefixConstant.PROMOTION_ONLINE_KEY, key);
        } catch (XbbException e) {
            paasRedisHelper.removeValue(RedisPrefixConstant.PROMOTION_ONLINE_KEY, key);
            throw e;
        } catch (Exception e) {
            paasRedisHelper.removeValue(RedisPrefixConstant.PROMOTION_ONLINE_KEY, key);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(),SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        if ((Objects.equals(online, BasicConstant.ONE))) {
            UserEntity creator = userModel.getByKey(userId, corpid);
            PaasFormEntityExt paasFormDataEntity = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode(), corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(), null);

            Runnable runnable = () -> {
                //创建信息
                try {
                    // 上架成功提醒超管，老板 消息推送 系统默认超管老板roleId=1，2?
                    List<UserEntity> managers = userModel.getUsersByRoleId(corpid, Arrays.asList(1,2));
                    List<String> userIdList = new ArrayList<>();
                    for (UserEntity manager : managers) {
                        userIdList.add(manager.getUserId());
                    }
                    userIdList.add(promotionActivityEntity.getCreatorId());
                    PushRefTypePojo.Options options = new PushRefTypePojo.Options(paasFormDataEntity.getAppId(), paasFormDataEntity.getMenuId(),
                            paasFormDataEntity.getId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(),
                            onlineDTO.getBusinessType(),onlineDTO.getBusinessType());
                    MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, userIdList, Collections.singletonList(dataId), 0,
                            null, I18nMessageUtil.getMessage(MarketingManagementPushConstant.PROMOTION_ACTIVITY_MANAGEMENT_ONLINE_PUSH_TITLE), String.format(I18nMessageUtil.getMessage(MarketingManagementPushConstant.PROMOTION_ACTIVITY_MANAGEMENT_ONLINE_PUSH_CONTENT),
                            creator.getName(),promotionActivityEntity.getName()), null, options);
                    baseProducer.sendMessage(PushTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT_ONLINE_PUSH, messageRabbitMqDTO);
                } catch (Exception e) {
                    LOG.error("促销上架消息推送", e);
                }

                //创建信息
                try {
                    JSONObject data = promotionActivityEntity.getData();
                    List<String> userIdList = marketingHelp.getPushUserIds(data, corpid);
                    PushRefTypePojo.Options options = new PushRefTypePojo.Options(paasFormDataEntity.getAppId(), paasFormDataEntity.getMenuId(),
                            paasFormDataEntity.getId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(),
                            onlineDTO.getBusinessType(),onlineDTO.getBusinessType());
                    DistributorMessageRabbitMqDTO distributorMessageRabbitMqDTO = new DistributorMessageRabbitMqDTO(corpid, userIdList, Collections.singletonList(dataId), 0,
                            null, I18nMessageUtil.getMessage(MarketingManagementPushConstant.DISTRIBUTOR_PROMOTION_ACTIVITY_MANAGEMENT_ONLINE_PUSH_TITLE), String.format(I18nMessageUtil.getMessage(MarketingManagementPushConstant.DISTRIBUTOR_PROMOTION_ACTIVITY_MANAGEMENT_ONLINE_PUSH_CONTENT),
                            promotionActivityEntity.getName()), null, options, DistributorMarkEnum.DISTRIBUTOR.getCode());
                    baseProducer.sendMessage(PushTypeEnum.DISTRIBUTOR_PROMOTION_ACTIVITY_MANAGEMENT_ONLINE_PUSH, distributorMessageRabbitMqDTO);
                } catch (Exception e) {
                    LOG.error("经销商端促销上架消息推送", e);
                }
            };
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
        }
    }

    private AfterSaveVO insert(MarketingManagementDataAddDTO marketingManagementDTO) throws XbbException {

        AfterSaveVO afterSaveVO = new AfterSaveVO();
        Integer businessType = marketingManagementDTO.getBusinessType();
        JSONObject data = marketingManagementDTO.getDataList();
        String corpid = marketingManagementDTO.getCorpid();
        String userId = marketingManagementDTO.getUserId();
        String userName = marketingManagementDTO.getLoginUserName();
        PromotionActivityEntity promotionActivityEntity = new PromotionActivityEntity();
        data.put(MarketingBaseEnum.STATUS.getAttr(), MarketingStatusEnum.WAIT_ONLINE.getCode());
        promotionActivityEntity.setName(data.getString(MarketingBaseEnum.NAME.getAttr()));
        promotionActivityEntity.setCorpid(corpid);
        promotionActivityEntity.setData(data);
        promotionActivityEntity.setStatus(MarketingStatusEnum.WAIT_ONLINE.getCode());
        promotionActivityEntity.setBusinessType(businessType);
        promotionActivityEntity.setBeginTime(data.getLong(MarketingBaseEnum.BEGIN_TIME.getAttr()));
        promotionActivityEntity.setEndTime(data.getLong(MarketingBaseEnum.END_TIME.getAttr()));
        promotionActivityEntity.setPriority(data.getInteger(MarketingBaseEnum.PRIORITY.getAttr()));
        promotionActivityEntity.setCreatorId(userId);
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode(), corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
        promotionActivityEntity.setFormId(paasFormEntityExt.getId());
        promotionActivityModel.insert(promotionActivityEntity);
        saveProduct(promotionActivityEntity, marketingManagementDTO.getProductArray(), corpid, false);
        String logName = promotionActivityEntity.getName();
        OperateTypeEnum operateTypeEnum = OperateTypeEnum.NEW;
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(),logName);
        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT, operateTypeEnum,
                promotionActivityEntity.getId().toString(), logName, memo, marketingManagementDTO.getHttpHeader());
        afterSaveVO.setFormDataId(promotionActivityEntity.getId());
        return afterSaveVO;
    }

    private void saveProduct(PromotionActivityEntity promotionActivityEntity, JSONArray productArray, String corpid, boolean isEdit) throws XbbException {
        Map<Long, PromotionProductEntity> originProductMap = new HashMap<>();
        Long refId = promotionActivityEntity.getId();
        if (isEdit) {
            List<PromotionProductEntity> dbList = promotionProductModel.getProductsByRefId(refId, corpid);
            dbList.forEach(item -> {originProductMap.put(item.getProductId(), item);});
        }
        List<Long> productIdList = new ArrayList<>();
        for (int i = 0; i < productArray.size(); i++){
            JSONObject jsonObject = productArray.getJSONObject(i);
            productIdList.add(jsonObject.getLong("dataId"));
        }
        Map<Long, PaasFormDataEntityExt> productMap = marketingHelp.marketingProductSaveMap(corpid, productIdList);
        List<PromotionProductEntity> addPromotionProductList = new ArrayList<>();
        List<PromotionProductEntity> updatePromotionProductList = new ArrayList<>();
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject productJSONObject = productArray.getJSONObject(i);
            Long productId = productJSONObject.getLong("dataId");
            boolean addProductFlag = !originProductMap.containsKey(productId);
            PromotionProductEntity promotionProductEntity;
            if (addProductFlag) {
                promotionProductEntity = new PromotionProductEntity();
                promotionProductEntity.setAddTime(DateTimeUtil.getInt());
                promotionProductEntity.setUpdateTime(DateTimeUtil.getInt());
                addPromotionProductList.add(promotionProductEntity);
            } else if (originProductMap.containsKey(productId)) {
                promotionProductEntity = originProductMap.get(productId);
                promotionProductEntity.setUpdateTime(DateTimeUtil.getInt());
                updatePromotionProductList.add(promotionProductEntity);
                originProductMap.remove(productId);
            } else {
                continue;
            }
            JSONObject productData = productMap.get(productId).getData();
            promotionProductEntity.setCorpid(corpid);
            promotionProductEntity.setBusinessType(promotionActivityEntity.getBusinessType());
            promotionProductEntity.setPriority(promotionActivityEntity.getPriority());
            promotionProductEntity.setProductId(productId);
            promotionProductEntity.setSort(i);
            promotionProductEntity.setParentId(productData.getLong(ProductEnum.PARENT_ID.getAttr()));
            promotionProductEntity.setCategoryId(productData.getLong(ProductEnum.CATEGORY_ID.getAttr()));
            promotionProductEntity.setRefId(refId);
            promotionProductEntity.setData(productJSONObject);
            promotionProductEntity.setDiscount(productJSONObject.getDouble(SelectProductEnum.DISCOUNT.getAttr()));
        }
        if (!addPromotionProductList.isEmpty()) {
            promotionProductModel.insertBatch(addPromotionProductList);
        }
        for (PromotionProductEntity promotionProductEntity : updatePromotionProductList) {
            promotionProductModel.update(promotionProductEntity);
        }
        for (Map.Entry<Long, PromotionProductEntity> entry : originProductMap.entrySet()) {
            PromotionProductEntity delProduct = entry.getValue();
            delProduct.setDel(1);
            promotionProductModel.update(delProduct);
        }
    }


    private JSONArray beforeSave(JSONObject dataList, Integer businessType, boolean isEdit, String corpid, PromotionActivityEntity oldPromotionActivityEntity) throws XbbException {
        List<Integer> disabledPriority = promotionActivityModel.getDisabledPriority(corpid, businessType);
        Integer oldPriority = null;
        if (Objects.nonNull(oldPromotionActivityEntity)) {
            oldPriority = oldPromotionActivityEntity.getPriority();
        }
        Double validaPriority = dataList.getDouble(MarketingBaseEnum.PRIORITY.getAttr());
        if (Math.round(validaPriority) != validaPriority || validaPriority < 1 || validaPriority > 50){
            throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500017);
        }
        Integer priority = dataList.getInteger(MarketingBaseEnum.PRIORITY.getAttr());
        for (Integer item : disabledPriority) {
            if (Objects.equals(priority, item) && !Objects.equals(oldPriority, item)) {
                throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500010);
            }
        }
                
        JSONArray productArray = saasSaveHelp.formatProductSave(dataList, MarketingBaseEnum.APPLICABLE_PRODUCT.getAttr());
        return productArray;
    }
}
